package middleware;

/**
 * Multicast project Bidois Morgan & Thomas Nunes
 *
 */
import Engine.TypeMessage;
import Test.I_RecvMsgHandler;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Thomas
 */
public class ServerThread extends MulticastManager implements I_ServerMulticastHandler, I_RecvMsgHandler {

    //CountClient fait la meme chose que le nbGroupClientCurrent dans le Nio mais si on change un truc ici au moins ca casse pas le nio ..
    private int countClient = 0;
    private int portForClient = 1500;

    public ServerThread() {
        try {
            InetAddress addr = InetAddress.getByName("localhost");
            this.InitializeAsServer(addr, 9090, this, this);

        } catch (IOException ex) {
        }
    }

    @Override
    public void test() {
        System.out.println("coucou handler server");
    }

    @Override
    /* send the directory to clients
     * the message  : Flag DIR - Adr - Port - Status - Adr 
     */
    public void sendDirectory() {
        String msgDir = "" + /*countClient +*/ directory.getDirectoryToSend();
        send2All(msgDir.getBytes(), TypeMessage.SEND_DIRECTORY);
    }

    @Override
    public void addClientToDirectory(InetAddress adr, int port) {
        ClientInfos client = new ClientInfos(countClient, adr, port);
        directory.addClient(client);
        countClient++;

        System.out.println(directory.toString());
    }

    @Override
    public void addClientToDirectory(int idClient) {
        ClientInfos client = null;
        try {
            client = new ClientInfos(idClient, InetAddress.getByName("localhost"), portForClient);
//            client = new ClientInfos(idClient, InetAddress.getByAddress("127.0.0.1".getBytes()), portForClient);
        } catch (UnknownHostException ex) {
            Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        directory.addClient(client);

        countClient++;
        portForClient++;

        System.out.println(directory.toString());
    }

    @Override
    public void printMsg(byte[] msg) {
        System.out.println("server a recu : " + new String(msg));
    }

    @Override
    public void receivedCB(byte[] data) {
        System.out.println("====Le serveur lit:" + new String(data) + " =====");
        System.out.println("Renvoi à tous les clients");
        send2All(data, TypeMessage.NORMAL);
    }
}